package com.cs.rabbitmq.simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {

    public static void main(String[] args) {
        //1: 创建连接工程
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        //2: 创建连接Connecton
        Connection connect = null;
        Channel channel = null;
        try {
            connect = connectionFactory.newConnection("生产者");
            /**
             * @params1 队列名称
             * @params2 是否持久化
             * @params3 排他性
             * @params4 是否自动删除
             * @params5 携带附属参数
             */
            //3: 获取通道 channel
            channel = connect.createChannel();
            String queueName = "queueA";
            //4: 创建交换机、声明队列、绑定关系、路由key、发送消息、接受消息
            channel.queueDeclare(queueName, false, false, false, null);
            //5: 准备消息内容
            String message = "Hello RabbitMq";
            //6: 发送消息给队列queue
            channel.basicPublish("", queueName, null, message.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //7: 关闭通道
            //8: 关闭连接
            if(channel != null  && channel.isOpen()){
                try {
                    channel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if(connect != null  && connect.isOpen()){
                try {
                    connect.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
